import { Repository } from 'typeorm';
import { AppDataSource } from '../../config/database';
import { HomeModule } from '../../entities/HomeModule';

export class HomeModuleService {
  private homeModuleRepository: Repository<HomeModule>;

  constructor() {
    this.homeModuleRepository = AppDataSource.getRepository(HomeModule);
  }

  /**
   * 获取首页模块列表
   */
  async getHomeModules(query: any = {}): Promise<{ modules: HomeModule[]; total: number }> {
    const { page = 1, pageSize = 10, type, isActive, moduleName } = query;
    
    const queryBuilder = this.homeModuleRepository.createQueryBuilder('module');
    
    // 添加类型过滤
    if (type !== undefined) {
      queryBuilder.andWhere('module.type = :type', { type });
    }
    
    // 添加状态过滤
    if (isActive !== undefined) {
      queryBuilder.andWhere('module.isActive = :isActive', { isActive });
    }
    
    // 添加模块名称搜索
    if (moduleName) {
      queryBuilder.andWhere('module.moduleName LIKE :moduleName', { moduleName: `%${moduleName}%` });
    }
    
    // 排序：按排序号升序，创建时间倒序
    queryBuilder.orderBy('module.sortOrder', 'ASC')
      .addOrderBy('module.createTime', 'DESC');
    
    // 分页
    const total = await queryBuilder.getCount();
    const modules = await queryBuilder
      .skip((page - 1) * pageSize)
      .take(pageSize)
      .getMany();

    return { modules, total };
  }

  /**
   * 获取首页模块详情
   */
  async getHomeModuleById(id: string): Promise<HomeModule | null> {
    return await this.homeModuleRepository.findOne({ where: { id } });
  }

  /**
   * 创建首页模块
   */
  async createHomeModule(moduleData: Partial<HomeModule>, userId: string): Promise<HomeModule> {
    const module = this.homeModuleRepository.create({
      ...moduleData,
      createBy: userId,
      updateBy: userId
    });
    
    return await this.homeModuleRepository.save(module);
  }

  /**
   * 更新首页模块
   */
  async updateHomeModule(id: string, moduleData: Partial<HomeModule>, userId: string): Promise<HomeModule | null> {
    const module = await this.getHomeModuleById(id);
    
    if (!module) {
      return null;
    }
    
    Object.assign(module, {
      ...moduleData,
      updateBy: userId
    });
    
    return await this.homeModuleRepository.save(module);
  }

  /**
   * 删除首页模块
   */
  async deleteHomeModule(id: string): Promise<boolean> {
    try {
      const result = await this.homeModuleRepository.delete(id);
      return result.affected ? result.affected > 0 : false;
    } catch (error) {
      console.error('删除首页模块失败:', error);
      return false;
    }
  }

  /**
   * 更新模块状态
   */
  async updateModuleStatus(id: string, isActive: boolean, userId: string): Promise<boolean> {
    try {
      const result = await this.homeModuleRepository.update(
        { id },
        { 
          isActive,
          updateBy: userId,
          updateTime: new Date()
        }
      );
      return result.affected ? result.affected > 0 : false;
    } catch (error) {
      console.error('更新模块状态失败:', error);
      return false;
    }
  }

  /**
   * 更新模块排序
   */
  async updateModuleSort(id: string, sortOrder: number, userId: string): Promise<boolean> {
    try {
      const result = await this.homeModuleRepository.update(
        { id },
        { 
          sortOrder,
          updateBy: userId,
          updateTime: new Date()
        }
      );
      return result.affected ? result.affected > 0 : false;
    } catch (error) {
      console.error('更新模块排序失败:', error);
      return false;
    }
  }
}

export const homeModuleService = new HomeModuleService(); 